package com.yanqu.road.server.manger.activity.tongbing;

import com.yanqu.road.dao.impl.player.UserCommonActivityDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.autodata.chuhan.data.ChuHanUserData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.activity.chuhan.ChuHanConfig;
import com.yanqu.road.logic.activity.chuhan.ChuHanMapLogic;
import com.yanqu.road.logic.bussiness.player.UserHistoryAttributeBussiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.rank.UnionRankMsgModel;
import com.yanqu.road.pb.activity.ChuHanProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tongbing.ChuHanModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityRankMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.ChuHanPb;
import com.yanqu.road.server.pb.TongBingPb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ChuHanMgr extends TempMgr {

    private static ChuHanConfig config = null;

    private static RandomHelper randomHelper = new RandomHelper();

    private static final Set<Long> userIdSet = new HashSet<>(); // 赚速有变化的玩家ID

    private static final Map<Integer, Set<Integer>> refreshGroupActivityMap = new ConcurrentHashMap<>();

    /**
     * 重新加载活动
     */
    public static void reloadActivityData() {
        getLogger().info("reload chuhan start");
        List<ActivityInfo> list = NormalActivityMgr.getOpenActivityInfoList(eActivityType.ChuHanZB.getValue());
        if (list.isEmpty()) {
            config = null;
            getLogger().info("reload chuhan end, no activity in show time.");
            return;
        }
        ActivityInfo activityInfo = list.get(0);

        loadConfigFromDb(activityInfo);
        getLogger().info("reload chuhan end, activityId {}.", config.getActivityInfo().getActivityId());

        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(ChuHanModule.class).chuHanLogin();
        }
    }

    /**
     * 数据库加载配置
     */
    private static void loadConfigFromDb(ActivityInfo activityInfo) {
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());

        ChuHanConfig tmpConfig = new ChuHanConfig(activityInfo, activityConfigMap, ChuHanMapLogic.getNpcEventPosNumConfig(), ChuHanMapLogic.getMapGraph());
        config = tmpConfig;
    }

    /**
     * 拿配置
     */
    public static ChuHanConfig getConfig() {
        return config;
    }

    /**
     * 拿活动信息
     */
    public static ActivityInfo getActivityInfo() {
        return config == null ? null : config.getActivityInfo();
    }


    /**
     * 刷新分组活动的在线玩家
     */
    public static void refreshGroupActivityOnlinePlayer() {
        if (config == null) {
            return;
        }

        ActivityInfo activityInfo = config.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }

        if (!UnionActivityGroupHelper.needGroup(activityInfo)) {
            return;
        }

        long groupTime = UnionActivityGroupHelper.getGroupTime(activityInfo);
        if (System.currentTimeMillis() < groupTime) {
            return;
        }

        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap == null) {
            return;
        }

        synchronized (refreshGroupActivityMap) {
            refreshGroupActivityMap.putIfAbsent(activityInfo.getActivityId(), new HashSet<>());
            Set<Integer> set = refreshGroupActivityMap.get(activityInfo.getActivityId());

            boolean needRefresh = false;
            ArrayList<Integer> groupIdList = new ArrayList<>(groupMap.keySet());
            for (int groupId : groupIdList) {
                if (!set.contains(groupId)) {
                    needRefresh = true;
                    break;
                }
            }

            if (needRefresh) {
                for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
                    player.getModule(ChuHanModule.class).chuHanLogin();
                }
                set.addAll(groupIdList);
            }
        }
    }


    /**
     * 是否为城主
     */
    public static boolean isMaster(long userId) {
        // 活动不存在或者不在活动期间内
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return false;
        }
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            return onlinePlayer.getModule(ChuHanModule.class).isChuHanMaster();
        } else {
            ChuHanUserData userActivityData = new UserCommonActivityDataDaoImpl<ChuHanUserData>().getUserActivityData(ChuHanUserData.class, config.getActivityInfo().getActivityId(), userId);
            if (userActivityData == null) {
                return false;
            }
            return userActivityData.getPositionId() == eTongBingPosition.Master.getValue();
        }
    }

    /**
     * 记录赚速有变化的商会
     */
    public static void addUnionEarnSpeedChange(long userId) {
        synchronized (userIdSet) {
            userIdSet.add(userId);
        }
    }


    /**
     * 获取膜拜奖励
     */
    public static String getWorshipReward(){
        Property rewardProperty = new Property();
        Map<Integer, List<Integer>> worshipRewardMap = config.getWorshipRewardMap();
        for(int goodsId : worshipRewardMap.keySet()){
            List<Integer> randomValueList = worshipRewardMap.get(goodsId);
            rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }

    /**
     * 商会能否变化人员
     */
    public static boolean canChangeUnion() {
        long now = System.currentTimeMillis();
        if (config != null
                && now > config.getJoinTimeList().get(1) // [报名期结束,活动结束] 无法退出
                && now < config.getActivityInfo().getEndTime() * 1000L) {
            return false;
        }
        return true;
    }

    /**
     * 是否是马
     */
    public static boolean isHorseItem(int goodsId) {
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (goodsInfo != null) {
            if (goodsInfo.getType() == eGoodsType.ChuHanHorse.getValue()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 加马
     */
    public static void addHorse(GamePlayer player, int goodsId, long count, int logType) {
        getLogger().info("chuhan add horse : userId {} goodsId {} count {} logType {}.", player.getUserId(), goodsId, count, logType);

        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }

        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (goodsInfo == null) {
            getLogger().error("tong bing add horse fail! no goodsInfo! userId {}.", player.getUserId());
            return;
        }
        int horseId = goodsInfo.getParamList().get(0).intValue();

        ChuHanProto.CrossChuHanChangeHorseReqMsg.Builder builder = ChuHanProto.CrossChuHanChangeHorseReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setHorse(horseId);
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_CHUHAN_UPDATE_HORSE, builder, config.getActivityInfo().getActivityId());
    }

    /**
     * 同步演武统兵门客数据
     * @param isRefreshMaxSoldier 是否只刷新兵力上限
     */
    public static void syncPatronsAbility(GamePlayer player, boolean isRefreshMaxSoldier) {
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (!config.inEnterActivityTime()) {
            return;
        }
        ChuHanProto.CrossChuHanUpdatePatronsReqMsg.Builder builder = ChuHanProto.CrossChuHanUpdatePatronsReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setUserId(player.getUserId());
        builder.addAllPatrons(ChuHanPb.parseChuHanPatronsListMsg(player.getModule(PatronsModule.class).getUserPatronsList()));
        builder.addAllSoldierAddition(player.getModule(PatronsModule.class).getChuHanSoldierAddition());
        builder.setIsRefreshMaxSoldier(isRefreshMaxSoldier);
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_CHUHAN_PATRONS_SYNC, builder, config.getActivityInfo().getActivityId());
    }

    public static void checkRegistrationList() {
        if (config == null || config.getActivityInfo() == null) {
            return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModel(activityInfo.getActivityId());
        if (null != model) {
            model.setRankNum(config.getUnionNum() + 20);
            model.setActivityEndTime(activityInfo.getEndShowTime());
            if (model.getRankListMsg().getRankListCount() == 0 && !model.isInReq()) {
                CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.Builder crossReqMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.newBuilder();
                crossReqMsg.setActivityId(activityInfo.getActivityId());
                crossReqMsg.addAllServerIds(activityInfo.getServerIdList());
                crossReqMsg.setRankNum(model.getRankNum());
                crossReqMsg.setActivityEndTime(activityInfo.getEndShowTime());
                GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_GET_MAX_ABILITY_UNION_RANK_LIST, crossReqMsg));
            }
        }

    }


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
